package com.lmb.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.lmb.bean.*;
import com.lmb.dao.*;
import com.lmb.dto.OrdersDto;
import com.lmb.exception.CustomException;
import com.lmb.service.OrdersService;
import com.sun.prism.impl.BaseContext;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpSession;
import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * @projectName: reggie
 * @package: com.lmb.service.impl
 * @className: OrdersServiceImpl
 * @author: Eric
 * @description: TODO
 * @date: 2022/9/21 19:29
 */
@Service
public class OrdersServiceImpl extends ServiceImpl<OrdersDao, Orders> implements OrdersService {
    @Autowired
    private UserDao userDao;
    @Autowired
    private OrdersDao ordersDao;

    @Autowired
    private ShoppingCartDao shoppingCartDao;

    @Autowired
    private AddressBookDao addressBookDao;

    @Autowired
    private OrderDetailDao orderDetailDao;


    public void submit(Orders orders, HttpSession session) {
        Long userId =(Long) session.getAttribute("user");

        User user = userDao.selectById(userId);
        if (user == null) {
            throw new CustomException("请先登录再下单！");
        }

        LambdaQueryWrapper<ShoppingCart> wrapper1 = new LambdaQueryWrapper<>();
        wrapper1.eq(ShoppingCart::getUserId, userId);
        List<ShoppingCart> carts = shoppingCartDao.selectList(wrapper1);
        if (carts == null || carts.size() == 0) {
            throw new CustomException("请先添加商品到购物车再下单！");
        }

        AddressBook addressBook = addressBookDao.selectById(orders.getAddressBookId());
        if (addressBook == null) {
            throw new CustomException("请正确填写地址后下单！");
        }

        long orderId = IdWorker.getId();
        AtomicInteger sumAmount = new AtomicInteger(0);

        carts.stream().forEach(cart -> {
            OrderDetail orderDetail = new OrderDetail();
            BeanUtils.copyProperties(cart, orderDetail, "id");
            orderDetail.setOrderId(orderId);

            sumAmount.addAndGet((cart.getAmount().multiply(new BigDecimal(cart.getNumber()))).intValue());
            orderDetailDao.insert(orderDetail);
        });


        orders.setId(orderId);
        orders.setNumber(UUID.randomUUID().toString());
        orders.setStatus(2);
        orders.setUserId(userId);
        orders.setOrderTime(LocalDateTime.now());
        orders.setCheckoutTime(LocalDateTime.now());
        orders.setAmount(new BigDecimal(sumAmount.get()));

        orders.setUserName(user.getName());
        orders.setPhone(addressBook.getPhone());
        orders.setAddress((addressBook.getProvinceName() == null ? "" : addressBook.getProvinceName()) +
                (addressBook.getCityName() == null ? "" : addressBook.getCityName()) +
                (addressBook.getDistrictName() == null ? "" : addressBook.getDistrictName()) +
                addressBook.getDetail()
        );
        orders.setConsignee(addressBook.getConsignee());

        this.save(orders);

        shoppingCartDao.delete(wrapper1);
    }

    @Override
    public Page<OrdersDto> userPage(Integer page, Integer pageSize, HttpSession session) {
        Long userId = (Long)session.getAttribute("user");
        Page<Orders> ordersPage = new Page<>(1,5);
        LambdaQueryWrapper<Orders> ordersLambdaQueryWrapper = new LambdaQueryWrapper<>();
        ordersLambdaQueryWrapper.eq(Orders::getUserId,userId);
        ordersLambdaQueryWrapper.orderByDesc(Orders::getOrderTime);
//        List<Orders> orders = ordersDao.selectList(ordersLambdaQueryWrapper);

        Page<Orders> orders = this.page(ordersPage,ordersLambdaQueryWrapper);

        Page<OrdersDto> ordersDtoPage = new Page<>();

        BeanUtils.copyProperties(orders,ordersDtoPage,"records");
        List<Orders> records = orders.getRecords();
        List<OrdersDto> ordersDtos = new ArrayList<>();

        records.forEach(orderItem -> {
            System.out.println(orderItem);
            OrdersDto ordersDto = new OrdersDto();
            BeanUtils.copyProperties(orderItem,ordersDto);
            LambdaQueryWrapper<OrderDetail> orderDetailLambdaQueryWrapper = new LambdaQueryWrapper<>();
            orderDetailLambdaQueryWrapper.eq(OrderDetail::getOrderId,orderItem.getId());
            List<OrderDetail> orderDetails = orderDetailDao.selectList(orderDetailLambdaQueryWrapper);
            ordersDto.setOrderDetails(orderDetails);
            ordersDtos.add(ordersDto);

        });
        ordersDtoPage.setRecords(ordersDtos);
        return ordersDtoPage;
    }
}
